package com.starblink.search.result.ui.widget

import android.content.Context
import android.graphics.Color
import android.view.*
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.TranslateAnimation
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.BaseVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.brv.DefaultDecoration
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.util.FontUtil
import com.starblink.search.config.SearchConfig
import com.starblink.search.databinding.PopGoodsSortBinding
import razerdp.basepopup.BasePopupWindow

import com.starblink.basic.style.R

class GoodsSortPop(
    context: Context,
    private val onSelect: ((sort: Int, text: String) -> Unit)? = null
) :
    BasePopupWindow(context) {

    private val binding = PopGoodsSortBinding.inflate(LayoutInflater.from(context))

    private val sorts = arrayListOf(
        SortModel(
            sort = SearchConfig.SORT_DEFAULT,
            select = true,
            text = context.string(R.string.recommended),
        ),
        SortModel(
            sort = SearchConfig.SORT_PRICE_DOWN,
            select = false,
            text = context.string(R.string.price_to_low),
        ),
        SortModel(
            sort = SearchConfig.SORT_PRICE_UP,
            select = false,
            text = context.string(R.string.price_to_high),
        ),
    )

    private val adapter by lazyOnNone {
        MutableAdapter(sorts).apply {
            addVhDelegate { viewGroup ->
                SortCell(viewGroup) {
                    notifyList(it)
                }
            }
        }
    }


    init {
        contentView = binding.root
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        setAlignBackground(true)
        setBackgroundColor(Color.parseColor("#AD0F172A"))
        // isOutSideTouchable = true

        binding.recycler.enableCorner(32.dp2px(), "bottom")
        binding.recycler.setBackgroundColor(
            ContextCompat.getColor(
                context,
                R.color.sk_gray0
            )
        )
        binding.recycler.addItemDecoration(DefaultDecoration(context).apply {
            startVisible = false
            endVisible = false
            this.setColor(context.color(R.color.sk_gray100))
            this.setMargin(start = 16.dp2px(), end = 16.dp2px())
            this.setDivider(1)
        })
        binding.recycler.adapter = adapter
        binding.recycler.layoutManager = LinearLayoutManager(context)
    }

    private fun notifyList(index: Int) {
        sorts.forEach { it.select = false }
        val select = sorts[index]
        select.select = true
        adapter.refreshAll()
        dismiss()
        onSelect?.invoke(select.sort, select.text)
    }

    override fun onCreateShowAnimation(): Animation = TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,
        0f,
        Animation.RELATIVE_TO_PARENT,
        0f,
        Animation.RELATIVE_TO_PARENT,
        -1f,
        Animation.RELATIVE_TO_PARENT,
        0f
    ).apply {
        interpolator = DecelerateInterpolator()
        duration = 300
    }

    override fun onCreateDismissAnimation(): Animation = TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,
        0f,
        Animation.RELATIVE_TO_PARENT,
        0f,
        Animation.RELATIVE_TO_PARENT,
        0f,
        Animation.RELATIVE_TO_PARENT,
        -1f
    ).apply {
        interpolator = DecelerateInterpolator()
        duration = 300
    }

    override fun onOutSideTouch(
        event: MotionEvent,
        touchInBackground: Boolean,
        isPressed: Boolean
    ): Boolean {
        return if (isAllowDismissWhenTouchOutside && isPressed) {
            this.dismiss()
            false
        } else {
            false
        }
    }


}

private data class SortModel(
    val sort: Int,
    var select: Boolean = false,
    val text: String,
)

private class SortCell(parent: ViewGroup, val onSelect: ((position: Int) -> Unit)? = null) :
    BaseVH<SortModel>(TextView(parent.context).apply {
        layoutParams =
            ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, 56.dp2px())
    }) {

    private val text = itemView as TextView

    val colorNormal = color(R.color.sk_gray500)
    val colorSelect = color(R.color.sk_red600)

    val selectDrawable =
        ContextCompat.getDrawable(itemView.context, R.mipmap.ic_goods_filter_confirm)

    init {
        FontUtil.setSansRegula(text)
        text.setPadding(16.dp2px(), 0, 16.dp2px(), 0)
        text.gravity = Gravity.CENTER_VERTICAL
        text.setTextColor(colorNormal)
        text.textSize = 16f
    }

    override fun onBind(model: SortModel, position: Int) {
        text.text = model.text
        if (model.select) {
            text.setTextColor(colorSelect)
            text.setCompoundDrawablesWithIntrinsicBounds(null, null, selectDrawable, null)
        } else {
            text.setTextColor(colorNormal)
            text.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }
        text.setOnClickListener {
            onSelect?.invoke(position)
        }
    }
}
